package com.ay.smartpark.sdk.common.utils;




import com.ay.smartpark.sdk.common.base.CommonConstant;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Optional;

public class CookieUtil {

    public static String getValue(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            Optional<String> optional = Arrays.stream(cookies).filter(cookie -> key.equals(cookie.getName())).map(cookie -> cookie.getValue()).findFirst();
            return null != optional && optional.isPresent() ? optional.get() : null;
        }
        return null;
    }

    public static void setValue(HttpServletResponse response, String key, String value) {
        Cookie cookie = new Cookie(key, value);
        cookie.setDomain(YmlUtils.getRoot_Domain(""));
        cookie.setHttpOnly(true);
        cookie.setMaxAge(CommonConstant.COOKIE_EXPIRE_TIME);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public static void setExpire(HttpServletRequest request, HttpServletResponse response, String key) {
        Cookie[] cookies = request.getCookies();
        Optional<Cookie> optionalCookie = Arrays.asList(cookies).stream().filter(c -> c.getName().equals(key.trim())).findFirst();
        if (optionalCookie.isPresent()) {
            Cookie cookie = optionalCookie.get();
            cookie.setDomain(YmlUtils.getRoot_Domain(""));
            cookie.setHttpOnly(true);
            cookie.setMaxAge(0);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
    }
}
